import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadCollaboration {
    private static NormalTime nt = new NormalTime();

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(new subtractPointsTask());
        executor.execute(new extraPointsTask());
        System.out.println("线程 1\t\t线程 2\t\t分数");
        executor.shutdown();
    }
    public static class extraPointsTask implements Runnable{
        public void run(){
            try {
                while (true) {
                    nt.extraPoints((int)(Math.random() * 10) + 1);
                    Thread.sleep(1000);
                }
            }
            catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static class subtractPointsTask implements Runnable{
        public void run() {
            while (true) {
                nt.subtractPoints((int)(Math.random() * 10) + 1);
            }
        }
    }
    private static class NormalTime{
        private static Lock lock = new ReentrantLock();
        private static Condition newIndividualScore = lock.newCondition();
        private static int score = 0;

        public int getScore(){return score;}

        public void subtractPoints(int points){
            lock.lock();
            try{
                while (score < points){
                    System.out.println("\t\t\t等待加分");
                    newIndividualScore.await();
                }
                score -=points;
                System.out.println("\t\t\t减分 " + points +
                        "\t\t" + getScore());
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            finally {
                lock.unlock();
            }
        }


        public void extraPoints(int points){
            lock.lock();
            try{
                score +=points;
                System.out.println("加分 " + points +
                        "\t\t\t\t\t" + getScore());
                newIndividualScore.signalAll();
            }
            finally {
                lock.unlock(); // Release the lock
            }

        }
    }
}
